package ichainpvdr

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/logging"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/comm"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/consenser"
	inodeImpl "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/inode"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/context"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
	"github.com/pkg/errors"
)

var logger = logging.NewLogger("ichainsdk")

type IChainProvider struct {
	providerContext context.Providers
	commManager     *comm.CachingConnector
}

func New(config ichain.EndpointConfig) *IChainProvider {
	idleTime := config.Timeout(ichain.ConnectionIdle)
	sweepTime := config.Timeout(ichain.CacheSweepInterval)

	return &IChainProvider{
		commManager: comm.NewCachingConnector(sweepTime, idleTime),
	}
}

func (f *IChainProvider) Initialize(providers context.Providers) error {
	f.providerContext = providers
	return nil
}

func (f *IChainProvider) Close() {
	logger.Debug("Closing comm manager...")
	f.commManager.Close()
}

func (f *IChainProvider) CommManager() ichain.CommManager {
	return f.commManager
}

func (f *IChainProvider) CreateInodeFromConfig(inodeCfg *ichain.NetworkInode) (ichain.Inode, error) {
	return inodeImpl.New(f.providerContext.EndpointConfig(), inodeImpl.FromInodeConfig(inodeCfg))
}

func (f *IChainProvider) CreateConsenserFromConfig(cfg *ichain.ConsenserConfig) (ichain.Consenser, error) {
	newConsenser, err := consenser.New(f.providerContext.EndpointConfig(), consenser.FromConsenserConfig(cfg))
	if err != nil {
		return nil, errors.WithMessage(err, "creating consenser failed")
	}
	return newConsenser, nil
}
